import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<MachineOrderViewState> buildReducer() {
  return asReducer(
    <Object, Reducer<MachineOrderViewState>>{
      MachineOrderViewAction.action: _onAction,
      MachineOrderViewAction.onGetData: _onGetData,
    },
  );
}

MachineOrderViewState _onAction(MachineOrderViewState state, Action action) {
  final MachineOrderViewState newState = state.clone();
  return newState;
}

MachineOrderViewState _onGetData(MachineOrderViewState state, Action action) {
  final MachineOrderViewState newState = state.clone();
  int page = action.payload['page'];
  List<MachineOrderItemModel> items = action.payload['items'];
  List<MachineOrderItemModel> result = [];
  items.forEach((model) {
    double charge = double.tryParse(model.chargeFee) ?? 0.0;
    if (charge == 0.0) result.add(model);
  });
  if (page == 1) {
    newState.items = result;
    newState.refreshController.finishRefresh();
  } else {
    List<MachineOrderItemModel> tmp = [];
    tmp.addAll(newState.items);
    tmp.addAll(result);
    newState.items = tmp;
  }
  newState.currentPage = page;
  newState.refreshController.finishLoad(noMore: items.length == 0);
  return newState;
}
